package com.anos.smsfun.activities;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.text.Spannable;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.anos.smsfun.R;
import com.anos.smsfun.adapter.IconListAdapter;
import com.anos.smsfun.cache.AppConfigs;
import com.anos.smsfun.cache.SMSFunDataCache;
import com.anos.smsfun.controller.DataRequestCallback;
import com.anos.smsfun.controller.ThreadManager;
import com.anos.smsfun.model.MessageItem;
import com.anos.smsfun.services.smsDeliveredReceiver;
import com.anos.smsfun.services.smsSentReceiver;
import com.anos.smsfun.task.DoingBackground;
import com.anos.smsfun.task.QueryUtils;
import com.anos.smsfun.utility.DefConstants;
import com.anos.smsfun.utility.EmoticonsMgr;
import com.anos.smsfun.utility.MyClipboardManager;
import com.anos.smsfun.utility.Utils;

public class ViewSmsConversationActivity extends Activity implements
		OnClickListener, AdapterView.OnItemClickListener {

	private LinearLayout l_layoutAddedItem;
	private ScrollView scrollView;
	private View l_left;
	private View l_right;
	private Button btnInsertIcon;
	private Button btnSend;
	private EditText edInputText;
	private LinearLayout l_add_layout_icon;
	// private ProgressBar pbLoadSMS;
	private ProgressDialog mDialogLoading;

	private MessageItem mMessageItemSelected = null;
	private ArrayList<MessageItem> mMessageItems = new ArrayList<MessageItem>();
	private String mPhoneSender = "";
	private String mNameDisplay = "";

	private SMSFunDataCache mSmsFunDataCache;
	private AppConfigs mAppConfigs;

	private BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;

	private String mTextCopied = "";
	private boolean mShowwingListIcon;
	private ArrayList<Integer> mArrIdIcons = new ArrayList<Integer>();

	@SuppressWarnings("unused")
	private boolean mIsListLoading = false;

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DefConstants.WHAT_SENT_RESULT_OK:
				getListMessageByPhone(mPhoneSender);
				break;

			case DefConstants.WHAT_SENT_RESULT_NO_SERVICE:
				getListMessageByPhone(mPhoneSender);
				break;

			case DefConstants.WHAT_RECEIVER_MSG:
				// String strMsg = (String) msg.obj;
				// if (Utils.converStandardNumber(strMsg).equals(
				// Utils.converStandardNumber(mPhoneSender))) {
				// Log.e("NHAN TIN NHAN", "aaaaaa");
				// }
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_conversation);

		Utils.setUpActionBar(this);

		// init
		mSmsFunDataCache = SMSFunDataCache.getInstance(this);
		mAppConfigs = AppConfigs.getInstance(this);

		mDialogLoading = new ProgressDialog(this);
		mDialogLoading.setMessage(getString(R.string.loading_sms));
		mDialogLoading.setCanceledOnTouchOutside(false);

		// find view id
		findViewIdAll();

		// get bundle
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			mPhoneSender = bundle
					.getString(DefConstants.ACTION_VIEW_CONVERSATION);
			if (!mPhoneSender.equals("")) {
				try {
					mPhoneSender = Utils.converStandardNumber(mPhoneSender);
					mNameDisplay = mSmsFunDataCache.getContactDetail(
							mPhoneSender).getDisplayName();
				} catch (Exception e) {
					mNameDisplay = mPhoneSender;
				}
				// set title view
				LayoutInflater inflator = (LayoutInflater) this
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View v = inflator.inflate(R.layout.title_view, null);
				((TextView) v.findViewById(R.id.tvTitle_ab))
						.setText(mNameDisplay);
				((TextView) v.findViewById(R.id.tvNumber_ab))
						.setText(mPhoneSender);
				getActionBar().setCustomView(v);

			}
		} else {

		}

	}

	private void findViewIdAll() {
		l_add_layout_icon = (LinearLayout) findViewById(R.id.layout_add_layout_icon);
		l_layoutAddedItem = (LinearLayout) findViewById(R.id.layout_added_item_msg);
		scrollView = (ScrollView) findViewById(R.id.scroll_Conversation);
		btnInsertIcon = (Button) findViewById(R.id.btnInsertIcon_conv);
		btnSend = (Button) findViewById(R.id.btnSend_conv);
		edInputText = (EditText) findViewById(R.id.edInputMSG_conv);
		// pbLoadSMS = (ProgressBar) findViewById(R.id.pbLoadSMS);

		btnInsertIcon.setOnClickListener(this);
		btnSend.setOnClickListener(this);
	}

	@SuppressWarnings("static-access")
	@Override
	protected void onResume() {
		// get data list
		if (!mPhoneSender.equals("")) {
			// get list data
			// pbLoadSMS.setVisibility(View.VISIBLE);
			mDialogLoading.show();

			mMessageItems.clear();
			getListMessageByPhone(mPhoneSender);
		} else {
			Toast.makeText(ViewSmsConversationActivity.this,
					R.string.loading_msg_error_toast, Toast.LENGTH_SHORT)
					.show();
			finish();
		}
		// clear notification
		NotificationManager notificationManager = (NotificationManager) this
				.getSystemService(this.NOTIFICATION_SERVICE);
		notificationManager.cancel(DefConstants.ID_NOTIFICATION_RECEIVED);

		super.onResume();
	}

	@Override
	protected void onPause() {
		try {
			if (smsSentReceiver != null) {
				unregisterReceiver(smsSentReceiver);
			}
			if (smsDeliveredReceiver != null) {
				unregisterReceiver(smsDeliveredReceiver);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		mMessageItems.clear();
		mMessageItems = null;
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_conv, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			overridePendingTransition(0, R.anim.exit_slide_right);
			break;

		case R.id.mnuItem_call:
			if (!mPhoneSender.equals("")) {
				Utils.callPhone(ViewSmsConversationActivity.this,
						mPhoneSender.trim());
			} else {
				Utils.showMessageDialog(ViewSmsConversationActivity.this,
						getString(R.string.can_not_call));
			}
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("Option");
		menu.add(Menu.NONE, DefConstants.MNU_CONTEXT_SMS_COPY_ID, Menu.NONE,
				getString(R.string.mnu_copytext));
		menu.add(Menu.NONE, DefConstants.MNU_CONTEXT_SMS_FORWARD_ID, Menu.NONE,
				getString(R.string.mnu_forward));
		menu.add(Menu.NONE, DefConstants.MNU_CONTEXT_SMS_DETAIL_ID, Menu.NONE,
				getString(R.string.mnu_viewdetail));
		menu.add(Menu.NONE, DefConstants.MNU_CONTEXT_SMS_DELETE_ID, Menu.NONE,
				getString(R.string.mnu_delete));
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case DefConstants.MNU_CONTEXT_SMS_COPY_ID:
			if (mMessageItemSelected != null) {
				mTextCopied = mMessageItemSelected.getBody();
				Toast.makeText(
						ViewSmsConversationActivity.this,
						ViewSmsConversationActivity.this
								.getString(R.string.toast_copied),
						Toast.LENGTH_SHORT).show();

				MyClipboardManager.copyToClipboard(
						ViewSmsConversationActivity.this, mTextCopied);
			}
			break;

		case DefConstants.MNU_CONTEXT_SMS_FORWARD_ID:
			Intent intent = new Intent(ViewSmsConversationActivity.this,
					NewMessagingActivity.class);
			intent.putExtra(DefConstants.ACTION_VIEW_FIND_CONTACT,
					mMessageItemSelected.getBody());
			startActivity(intent);
			overridePendingTransition(0, R.anim.exit_slide_left);
			finish();
			break;

		case DefConstants.MNU_CONTEXT_SMS_DETAIL_ID:
			Utils.showDialogInfoMsg(ViewSmsConversationActivity.this,
					mMessageItemSelected);
			break;

		case DefConstants.MNU_CONTEXT_SMS_DELETE_ID:
			if (mMessageItemSelected != null) {
				QueryUtils.deleteMessage(ViewSmsConversationActivity.this,
						mMessageItemSelected.getId());
				getListMessageByPhone(mPhoneSender);
			}
			break;

		default:
			break;
		}
		return true;
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(0, R.anim.exit_slide_right);
		return;
	}

	/**
	 * get list message by phone
	 */
	private void getListMessageByPhone(String phoneNumber) {
		mIsListLoading = true;
		mMessageItems.clear();
		DoingBackground.readAllSMSByPhone(ViewSmsConversationActivity.this,
				phoneNumber, onDataListResult);
	}

	private DataRequestCallback<ArrayList<MessageItem>> onDataListResult = new DataRequestCallback<ArrayList<MessageItem>>() {

		@Override
		public void onResult(ArrayList<MessageItem> result,
				boolean continueWaiting) {
			// pbLoadSMS.setVisibility(View.GONE);
			if (mDialogLoading.isShowing())
				mDialogLoading.dismiss();

			if (result != null && !result.isEmpty()) {
				mMessageItems.addAll(result);
				refreshDataList();

				// update msg (danh dau da doc)
				updateSeenAllSMS();
			} else {
				if (!continueWaiting) {
					// Có lỗi xảy ra khi request dữ liệu
					Toast.makeText(ViewSmsConversationActivity.this,
							R.string.loading_msg_error_toast,
							Toast.LENGTH_SHORT).show();
				}
			}

			mIsListLoading = continueWaiting;
		}
	};

	/**
	 * refresh list khi co data moi
	 */
	private void refreshDataList() {
		if (mMessageItems == null || mMessageItems.isEmpty())
			return;

		// duyet list de add vao layout
		l_layoutAddedItem.removeAllViews();
		for (int i = mMessageItems.size() - 1; i >= 0; i--) {
			final MessageItem msgItem = mMessageItems.get(i);

			addMessageItemToList(msgItem);
		}

		// scroll xuống tin nhắn cuối cùng
		scrollView.post(new Runnable() {
			@Override
			public void run() {
				scrollView.fullScroll(ScrollView.FOCUS_DOWN);
			}
		});
	}

	/**
	 * add a msg
	 */
	private void addMessageItemToList(final MessageItem msgItem) {
		if (msgItem.getType() == 1) {// msg cua ngta
			l_left = getLayoutInflater().inflate(
					R.layout.item_conversation_left, null);
			l_left.setId(msgItem.getId());
			final TextView tvBody = (TextView) l_left
					.findViewById(R.id.tvBody_conv_left);
			TextView tvTime = (TextView) l_left
					.findViewById(R.id.tvTime_conv_left);
			tvTime.setText(msgItem
					.getFormatDate(DefConstants.DATE_FORMAT_DDMMHHMM));
			Spannable textBody = EmoticonsMgr.getSmiledText(
					ViewSmsConversationActivity.this, msgItem.getBody());
			tvBody.setText(textBody);

			// long click
			tvBody.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					mMessageItemSelected = msgItem;
					registerForContextMenu(tvBody);
					return false;
				}
			});

			l_layoutAddedItem.addView(l_left);
		} else {// msg cua minh
			l_right = getLayoutInflater().inflate(
					R.layout.item_conversation_right, null);
			l_right.setId(msgItem.getId());
			final TextView tvBody = (TextView) l_right
					.findViewById(R.id.tvBody_conv_right);
			TextView tvTime = (TextView) l_right
					.findViewById(R.id.tvTime_conv_right);
			TextView tvStatus = (TextView) l_right
					.findViewById(R.id.tvIsSending_conv_right);
			tvTime.setText(msgItem
					.getFormatDate(DefConstants.DATE_FORMAT_DDMMHHMM));

			Spannable textBody = EmoticonsMgr.getSmiledText(
					ViewSmsConversationActivity.this, msgItem.getBody());
			tvBody.setText(textBody);

			// status
			if (msgItem.getStatus() == 32)
				tvStatus.setVisibility(View.VISIBLE);
			else
				tvStatus.setVisibility(View.GONE);

			// long click
			tvBody.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					mMessageItemSelected = msgItem;
					registerForContextMenu(tvBody);
					return false;
				}
			});

			l_layoutAddedItem.addView(l_right);
		}
	}

	/**
	 * check invalid input msg
	 */
	private boolean checkInvalidInput() {
		final String strText = edInputText.getText().toString();
		if (strText.trim().equals("")) {
			return false;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnInsertIcon_conv:
			includeLayoutAddIcon();
			break;

		case R.id.btnSend_conv:
			if (checkInvalidInput()) {
				MessageItem msgItem = new MessageItem();
				msgItem.setAddress(mPhoneSender);
				msgItem.setType(2);
				msgItem.setLongDate(System.currentTimeMillis());
				msgItem.setNameDisplay(mNameDisplay);
				msgItem.setBody(edInputText.getText().toString() + "");
				msgItem.setStatus(-1);
				msgItem.setSeen(1);

				// refresh list
				edInputText.setText("");
				mMessageItems.add(0, msgItem);
				// refreshDataList();
				addMessageItemToList(msgItem);
				// scroll xuống tin nhắn cuối cùng
				scrollView.post(new Runnable() {
					@Override
					public void run() {
						scrollView.fullScroll(ScrollView.FOCUS_DOWN);
					}
				});

				// insert
				QueryUtils.insertSmsSentItem(ViewSmsConversationActivity.this,
						msgItem);

				// send msg
				sendSMS(msgItem);

			}
			break;

		default:
			break;
		}
	}

	/**
	 * update cac tin nhan da doc (danh dau seen = 1)
	 */
	private void updateSeenAllSMS() {
		ThreadManager atm = ThreadManager.getInstance(this);
		atm.execute(new Runnable() {

			@Override
			public void run() {
				for (MessageItem item : mMessageItems) {
					if (item.getSeen() == 0) {
						// update db
						item.setSeen(1);
						QueryUtils.updateSmsSeen(
								ViewSmsConversationActivity.this, item);
						// update notification count
						int count = mAppConfigs.getNotifiCount();
						if (count > 0){
							count--;
							mAppConfigs.setNotifiCount(count);
						}
						Utils.setBadge(ViewSmsConversationActivity.this, count);
					}
				}
			}
		});
	}

	/**
	 * *********************** ICON ***********************
	 */
	// load list icon
	private void includeLayoutAddIcon() {
		if (mShowwingListIcon) {
			l_add_layout_icon.removeAllViews();
			mShowwingListIcon = false;
			// show keyboard
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.showSoftInput(edInputText, 0);
		} else {
			// hide keyboard
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(edInputText.getWindowToken(), 0);

			// include view
			View view = getLayoutInflater().inflate(
					R.layout.layout_display_icon, null);
			GridView gvIconList = (GridView) view.findViewById(R.id.gvListIcon);
			gvIconList.setOnItemClickListener(this);

			// numscolumn
			float scalefactor = getResources().getDisplayMetrics().density * 60;
			@SuppressWarnings("deprecation")
			int number = getWindowManager().getDefaultDisplay().getWidth();
			int columns = (int) ((float) number / (float) scalefactor);
			gvIconList.setNumColumns(columns);

			// load all icon
			mArrIdIcons = EmoticonsMgr.getListIcons(this);

			IconListAdapter adapter = new IconListAdapter(this, mArrIdIcons);
			gvIconList.setAdapter(adapter);

			l_add_layout_icon.addView(view);
			mShowwingListIcon = true;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
		final int id = mArrIdIcons.get(i);

		int cursorPosition = edInputText.getSelectionStart();
		String tempFirst = edInputText.getText().toString()
				.substring(0, cursorPosition);
		String tempLast = "";
		if (cursorPosition < edInputText.getText().length())
			tempLast = edInputText.getText().toString()
					.substring(cursorPosition, edInputText.getText().length());

		tempFirst += EmoticonsMgr.getKeyByValue(id);
		tempFirst += tempLast;

		edInputText.setText(EmoticonsMgr.getSmiledText(this, tempFirst));
		edInputText.setSelection(edInputText.getText().length());
	}

	// ////////////////////////////////////////////////////////////////
	// SEND SMS
	// ////////////////////////////////////////////////////////////////

	/**
	 * send sms to another device
	 */
	private void sendSMS(final MessageItem msgItem) {
		ThreadManager tm = ThreadManager
				.getInstance(ViewSmsConversationActivity.this);
		tm.execute(new Runnable() {

			@Override
			public void run() {
				try {
					final int MAX_SMS_MESSAGE_LENGTH = 160;
					final String SENT = "SMS_SENT";
					final String DELIVERED = "SMS_DELIVERED";

					PendingIntent sentPI = PendingIntent.getBroadcast(
							ViewSmsConversationActivity.this, 0, new Intent(
									SENT), 0);
					PendingIntent deliveredPI = PendingIntent.getBroadcast(
							ViewSmsConversationActivity.this, 0, new Intent(
									DELIVERED), 0);

					smsSentReceiver = new smsSentReceiver(msgItem, mHandler);
					smsDeliveredReceiver = new smsDeliveredReceiver(msgItem);

					/**
					 * --when the SMS has been sent
					 */
					registerReceiver(smsSentReceiver, new IntentFilter(SENT));

					/**
					 * --when the SMS has been delivered
					 */
					registerReceiver(smsDeliveredReceiver, new IntentFilter(
							DELIVERED));

					SmsManager smsManager = SmsManager.getDefault();
					int length = msgItem.getBody().length();
					if (length > MAX_SMS_MESSAGE_LENGTH) {
						ArrayList<String> messagelist = smsManager
								.divideMessage(msgItem.getBody());
						smsManager.sendMultipartTextMessage(
								msgItem.getAddress(), null, messagelist, null,
								null);
					} else {
						smsManager.sendTextMessage(msgItem.getAddress(), null,
								msgItem.getBody(), sentPI, deliveredPI);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

	}

}
